<template>
  <div class="content" ref="contentRef">
    <div class="header" @click="handleHeaderClick">
      <div class="user" :style="{ backgroundColor: generateEmailColor(email.fromEmailName) }">
        {{email.fromEmailName.slice(0, 1)}}
      </div>
      <div>
        
      </div>
      <div class="header_con">
        <div class="row">
          <div class="sTitle" @click.stop="">
            <span v-if="!email.isSeen" class="status"></span>
            <account :sentDate="email.sentDate" :emailName="email.fromEmailName" :email="email.fromEmail" />
            <span class="date ml8">{{ email.sentDate }}</span>
            <i class="iconfont icon-file" @click="handlerToFile()" v-if="email.annexNum" />
          </div>
          <div class="operate-wrap">
            <!-- <span v-if="customerVisable" @click.stop="handleInquiry" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg" v-loading="inquiryLoading"><i class="iconfont icon-inquiry" />提取询盘</span> -->
            <!-- <span v-loading="fileLoading" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg" v-if="email.annexList.length && customerVisable" @click.stop="handlerSelectFile"><i class="iconfont icon-order" />订单提取</span> -->
            <span v-if="email.isSeen" @click.stop="handleClick(email, 'unRead')"><i class="iconfont icon-unread" />标为未读</span>
            <span @click.stop="handleClick(email, 'reply')"><i class="iconfont icon-replay" />回复</span>
            <span @click.stop="handleClick(email, 'replyAll')"><i class="iconfont icon-replay-all" />回复全部</span>
            <span @click.stop="handleClick(email, 'forward')"><i class="iconfont icon-forward" />转发</span>
          </div>
        </div>
        <div  class="row">
          <div class="receiver">
            <span @click.stop="">
              发给 
              <account :emailName="email.toEmailName" :email="email.toEmail" />
            </span>
            <span class="receiver" @click.stop="" v-if="email.ccEmail.length">
              &nbsp;&nbsp;抄送 
              <span class="mr10" v-for="item in email.ccEmail">
                <account :emailName="item.name" :email="item.email" />
              </span>
            </span>
          </div>

        </div>
      </div>
    </div>
    <div v-if="isCollapse" class="htmls">
      <ShadowDom @click="handleView" @dblclicked="handleDbClick" :htmlContent="contentHtml" />
    </div>
    <div ref="attachRef" v-if="isCollapse && email.annexList.length">
      <div class="attachment_title">附件</div>
      <div class="attachment_wrap">
        <attachment :file="annex" v-for="(annex, index) in email.annexList" :key="index" />
      </div>
    </div>
    <AddInquiryModal ref="AddInquiryModalRef" :emailId="email.id" :inquiryInfo="inquiryInfo" :type="addType" @close="AddInquiryModalRef.value.showDialog = false" />
    <AttachmentModal ref="AttachmentModalRef" :list="email.annexList" @submit="handleOrder" @close="AttachmentModalRef.value.showDialog = false" />
  </div>
</template>
<script lang="ts" setup>
import { defineProps, ref, onMounted, defineAsyncComponent, watch } from 'vue';

import { openWeb, previewImg } from '/@/utils/webView';
import api from "/@/api/email/index";
import ShadowDom from "./shadowDom.vue";
import account from "./account.vue";
import attachment from './attachment.vue';
import { ElMessage } from 'element-plus';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores';
import { generateEmailColor } from '/@/utils/colorGenerator';

const AddInquiryModal = defineAsyncComponent(() => import('./addModal.vue'));
const AttachmentModal = defineAsyncComponent(() => import('./attachmentModal.vue'));

const props = defineProps({
  email: {
    type: Object,
    default: {},
  },
  observer: {
    type: Boolean,
    default: true,
  },
  index: {
    type: Number,
    default: 0,
  },
});

const contentRef = ref();
const isCollapse = ref(false);
const isContentLoaded = ref(false); // 标记内容是否已加载
const attachRef = ref();
const contentHtml = ref('');
const AddInquiryModalRef = ref()
const AttachmentModalRef = ref()

const inquiryInfo = ref<any>({});
const stores = useEmail(pinia);
const addInquiryVisable = ref(false);
const addType = ref('');

const customerVisable = !props.email.fromEmail.includes(stores.curAccount);

const emit = defineEmits(['onClick', 'onScrollTo', 'setReadStatus']);

const handleClick = (emial: any, action: string) => emit( 'onClick', emial, action);

// 询盘loading
// const inquiryLoading = ref(false);
// 订单提取loading
const fileLoading = ref(false);

// 处理邮件标题点击事件
const handleHeaderClick = async () => {
  // 如果内容尚未加载，则加载内容
  if (!isContentLoaded.value) {
    await getDetail();
    // console.log('setReadStatus', props.email)
    emit('setReadStatus', props.email);
  } else {
    // 如果内容已加载，则切换展开/折叠状态
    isCollapse.value = !isCollapse.value;
  }
};

const handleView = (e: any) => {
  const aTag = e.target.closest('a');
  if (aTag) {
    const href = aTag.getAttribute('href').trim() || '';
    if (href.includes('http')) {
      e.preventDefault();
      openWeb(href);
    }
  }
};

const handleDbClick = (event: any) => {
  if (event.target instanceof HTMLElement && event.target.tagName.toLowerCase() === 'img') {
    previewImg(event.target.src);
  }
};

const handlerToFile = () => {
  if (attachRef.value) {
    emit( 'onScrollTo', attachRef.value.offsetTop - 150);
  }
};

const getDetail = async () => {
  // console.log(props.email.id)
  const res = await api.email.getBody(props.email.id);
  if (res.code === 200) {
    isContentLoaded.value = true;
    isCollapse.value = true;
    contentHtml.value = res.data || ''; 
    console.log(contentHtml)
  }
}

const initObserver = () => {
  // 只对第一封邮件使用IntersectionObserver自动加载
  if (props.index === 0) {
    const options = {
      threshold: 0.1
    };
    if (contentRef.value) {
      const observer = new IntersectionObserver(entryList => {
        const entry = entryList[0];
        if (entry.isIntersecting) {
          getDetail();
          observer.disconnect();
        }
      }, options);
      observer.observe(contentRef.value);
    }
  }
};

onMounted(() => {
  if (props.observer) {
    // 只为第一封邮件初始化Observer
    if (props.index === 0) {
      initObserver();
    }
  } else {
    isContentLoaded.value = true;
    isCollapse.value = true;
    contentHtml.value = props.email.bodyText;
  }
});

// const handleCustomer = async () => {
//   addType.value = 'customer';
//   addInquiryVisable.value = true;
// };

const handleOrder = async (annex: any) => {
  AttachmentModalRef.value.showDialog = false;
  fileLoading.value = true;
  let docPromise;
  // 没有地址需要先下载
  if (!annex.fileUrl) {
    docPromise = api.email.download({
        account: stores.curAccount,
        annexId: annex.id
      }).then(() => api.inquiry.getDocExtract(annex.id));
  }
  else {
    docPromise = api.inquiry.getDocExtract(annex.id);
  }

  let res;
  try {
    res = await docPromise;
  } catch {}
  
  fileLoading.value = false;
  if (res && res.code === 200) {
    if (res.data['采购编号'] === '未找到') {
      ElMessage({ type: 'info', message: '没有提取到订单信息！' });
    } else {
      const infoList = res.data['产品信息'];
      const otherInfo = {
          '收件信息': res.data['收件信息'],
          '采购编号': res.data['采购编号'],
          '订单总价': res.data['订单总价'],
          '订单交期': res.data['订单交期'],
      };
      const data = {
        num: infoList[0]['产品数量'],
        productName: infoList[0]['产品名称'],
        productCode: infoList[0]['产品编号'],
        otherInfo: JSON.stringify(otherInfo)
      };
      inquiryInfo.value = data;
      addType.value = 'order';
      AddInquiryModalRef.value.showDialog = true
      AddInquiryModalRef.value.init()
    }
  }
};

// const handleInquiry = async () => {
//   inquiryLoading.value = true;
//   let res: any = {};
//   try {
//      res = await api.inquiry.isInquiry(props.email.id);
//   } catch {}

//   inquiryLoading.value = false;
//   if (res.code === 200) {
//     if (res.data.isInquiry === 1) {
//       const data = JSON.parse(res.data.inquiryData);
//       data.productCode = data.productNo;
//       inquiryInfo.value = data;
//       addType.value = 'inquiry';
//       addInquiryVisable.value = true;
//     } else {
//       ElMessage({ type: 'info', message: '没有提取到询盘信息！' });
//     }
//   }
// };

watch(
  () => props.email,
  async (newVal) => {
    // console.log('email变化了', newVal)
    if(!newVal.isSeen) {
      isCollapse.value = false;
      isContentLoaded.value = false;
      contentHtml.value = '';
    }
  },
  { deep: true }
)

// const handlerToSwitchStatus = () => {
//   isCollapse.value = false;
//   console.log('关闭啦')
// }

// const getEmailColor = (emailName: string) => {
//   const hash = emailName.charCodeAt(0) % 10;
//   const colors = ['#FF69B4', '#33CC33', '#6666CC', '#CC3333', '#CCCC33', '#33CCCC', '#CC66CC', '#CCCC66', '#666666', '#CCCCCC'];
//   return colors[hash];
// }
// defineExpose({ handlerToSwitchStatus });
</script>
<style lang="scss" scoped>
.content {
  background-color: #fff;
  border: 1px solid #E7E7E7;
  border-radius: 4px;
  padding: 5px;
  .user {
    color: #fff;
    border-radius: 50%;
    height: 36px;
    width: 36px;
    text-align: center;
    line-height: 36px;
    font-weight: bold;
    margin-right: 10px;
    font-size: 24px;
  }
  .status {
    width: 8px;
    height: 8px;
    background: #f73131;
    display: inline-block;
    border-radius: 50%;
    margin-right: 4px;
  }

  .header {
    position: sticky;
    display: flex;
    top: 0;
    padding: 6px 10px;
    background-color: #fff;
    z-index: 111;
    .header_con {
      flex: 1;
    }
    .row {
      display: flex;
      justify-content: space-between;
      font-size: 12px;

      &:nth-of-type(2) {
        padding: 4px 0;
        border-bottom: 1px dashed #dbdddd;
      }

      .sTitle {
        font-weight: 700;
      }

      .date {
        color: #606266;
        font-weight: normal;
      }
    }
  }
}

.operate-wrap {
  display: flex;
  justify-content: flex-end;
  span {
    padding: 0 10px;
    margin-left: 10px;
    color: #3f464d;
    font-weight: normal;
    cursor: pointer;
    font-size: 14px;
    height: 26px;
    display: flex;
    align-items: center;
    &:hover {
      color: #80ADFF;
    }
  }
  &.padding {
    padding-right: 10px;
    padding-bottom: 10px;
  }

  .iconfont {
    font-size: 20px;
  }
}

.mr10 {
  margin-right: 10px;
}

.receiver {
  flex: 1;
}

.icon-file {
  font-size: 12px;
  margin: 0 5px;
  color: #fca146;
}

.htmls {
  padding: 0 10px 6px;
  overflow: hidden;
}

.attachment_wrap {
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
}

.attachment_title {
  font-weight: bold;
  padding-left: 10px;
}
</style>